import { useState } from "react"
import { Button, Form, Input, message } from "antd"
import { KeyOutlined, UserOutlined } from "@ant-design/icons"
import { useNavigate } from "react-router"
import imgLogo from '@/common/images/logo.png'
import imgCover from './cover.svg'
import './login.styl'
import { signIn, getMenuList } from '@/api/user'
import { useDispatch } from 'react-redux'
import { setMenu } from '@/store/slices/menu'

function Login() {
  const navigate = useNavigate()

  const dispatch = useDispatch()

  const [loading, setLoading] = useState(false)

  const loginSubmit = async(values) => {
    setLoading(true)

    console.log('submitData', values)

    const data = await signIn(values)

    const menuData = await getMenuList()

    dispatch(setMenu(menuData.data))

    if(data.code === 0) {
      localStorage.setItem('userLoginInfo',
        JSON.stringify({
          uid: data.data.userData.id,
          nickname: data.data.userData.username,
          token: data.data.token
        })
      )
      console.log(data)
      setLoading(false)
      navigate('/home')
    } else {
      message.error({
        content: data.msg
      })
      setLoading(false)
    }
  }

  const toRegister = () => {
    console.log('注册')
    navigate('/register')
  }

  return (
    <div className="P-login">
      <div className="login-con">
        <div className="cover-con">
          <img src={ imgLogo } alt="" className="img-logo" />
          <h2>Vite React APP</h2>
          <img src={ imgCover } alt="" className="img-cover" />
          <div className="m-footer">嘻嘻哈哈小郭子</div>
        </div>
        <div className="pannel-con">
          <h3>Welcome!</h3>
          <p className="subtext">请登录您的账号</p>
          <Form onFinish={ loginSubmit }>
            <Form.Item name="username" rules={ [{ required: true, message: '请输入您的账号' }] }>
              <Input size="large" placeholder="请输入账号" prefix={ <UserOutlined /> }></Input>
            </Form.Item>
            <Form.Item name='password' rules={ [{ required: true, message: '请输入密码' }] }>
              <Input.Password size="large" placeholder="请输入密码" prefix={ <KeyOutlined/> }></Input.Password>
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit" size="lagre" block={ true } loading={ loading }>登录</Button>
            </Form.Item>
            <Button type="link" size="lagre" block={ true } onClick={ toRegister }>去注册</Button>
          </Form>
        </div>
      </div>
    </div>
  )
}

export default Login
